<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 实测实量统计分析 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData :searchData="searchArr" @search="search"></searchData>
      <!-- 表格 -->
      <a-card :bordered="false">
        <div class="statistics-top">
          <title-name title="统计信息"></title-name>
          <a-button type="primary" :loading="statisticsListLoading" @click="statisticsList"> 提交汇总统计 </a-button>
        </div>
        <a-row>
          <a-col :span="4">
            <div class="statistics-left">
              <h2 style="margin-right: 20px;">组织架构</h2>
              <a-button type="danger" icon="lock" ghost v-if="!lockLeft" @click="lockChange('left')"> 锁定 </a-button>
              <a-button type="primary" icon="unlock" ghost v-if="lockLeft" @click="lockChange('left')"> 解锁 </a-button>
            </div>
            <a-input-search style="margin-bottom: 8px" size="large" placeholder="请输入" @change="onSearchLeft" />
            <a-spin :spinning="spinningLeft" tip="加载中...">
              <a-tree
                ref="treeLeft"
                style="border: 1px solid rgba(215, 215, 215, 1);min-height: 500px;"
                :expanded-keys="expandedKeysLeft"
                :auto-expand-parent="autoExpandParentLeft"
                :tree-data="treeDataLeft"
                :load-data="onLoadDataLeft"
                :replace-fields="replaceFields"
                @expand="onExpandLeft"
                @select="onSelectLeft"
              >
                <template slot="title" slot-scope="scopes">
                  <span v-if="scopes[replaceFields.title].indexOf(searchValueLeft) > -1">
                    {{ scopes[replaceFields.title].substr(0, scopes[replaceFields.title].indexOf(searchValueLeft)) }}
                    <span style="color: #f50">{{ searchValueLeft }}</span>
                    {{ scopes[replaceFields.title].substr(scopes[replaceFields.title].indexOf(searchValueLeft) + searchValueLeft.length) }}
                  </span>
                  <span v-else>{{ scopes[replaceFields.title] }}</span>
                  <a-icon
                      v-if="statisticsListLockLeftId === scopes[replaceFields.key] && lockLeft"
                      type="lock"
                      style="margin: 4px; color: #0E7ED0"
                    />
                </template>
              </a-tree>
            </a-spin>
          </a-col>
          <a-col :span="16" style="padding: 0 10px;margin-top: 52px;">
            <a-spin :spinning="statisticsListLoading" tip="加载中...">
              <div v-if="Object.keys(details).length > 0">
                <div v-for="(val, key) in details" :key="key">
                  <title-name :title="key"></title-name>
                  <!-- 表格 -->
                  <a-table bordered  v-if="val != null" :data-source="Array.isArray(val) ? val : [val]" :columns="columns" rowKey="id" size="default" style="width: 100%; overflow-x: auto;margin-bottom: 20px;" :pagination="false"></a-table>
                </div>
              </div>
              <div v-else>
                <title-name title="汇总"></title-name>
                <!-- 表格 -->
                <a-table bordered :data-source="[]" :columns="columns" rowKey="id" size="default" style="width: 100%; overflow-x: auto;" :pagination="false"></a-table>
              </div>
            </a-spin>
          </a-col>
          <a-col :span="4">
            <div class="statistics-left">
              <h2 style="margin-right: 20px;">工程构成</h2>
              <a-button type="danger" icon="lock" ghost v-if="!lockRight" @click="lockChange('right')"> 锁定 </a-button>
              <a-button type="primary" icon="unlock" ghost v-if="lockRight" @click="lockChange('right')"> 解锁 </a-button>
            </div>
            <a-input-search style="margin-bottom: 8px" size="large" placeholder="请输入" @change="onSearchRight" />
            <a-spin :spinning="spinningRight" tip="加载中...">
              <a-tree
                ref="treeRight"
                style="border: 1px solid rgba(215, 215, 215, 1);min-height: 500px;"
                :expanded-keys="expandedKeysRight"
                :auto-expand-parent="autoExpandParentRight"
                :tree-data="treeDataRight"
                :load-data="onLoadDataRight"
                :replace-fields="replaceFields"
                @expand="onExpandRight"
                @select="onSelectRight"
              >
              <template slot="title" slot-scope="scopes">
                  <span v-if="scopes[replaceFields.title].indexOf(searchValueRight) > -1">
                    {{ scopes[replaceFields.title].substr(0, scopes[replaceFields.title].indexOf(searchValueRight)) }}
                    <span style="color: #f50">{{ searchValueRight }}</span>
                    {{ scopes[replaceFields.title].substr(scopes[replaceFields.title].indexOf(searchValueRight) + searchValueRight.length) }}
                  </span>
                  <span v-else>{{ scopes[replaceFields.title] }}</span>
                  <a-icon
                      v-if="statisticsListLockRightId === scopes[replaceFields.key] && lockRight"
                      type="lock"
                      style="margin: 4px; color: #0E7ED0"
                    />
                </template>
              </a-tree>
            </a-spin>
          </a-col>
        </a-row>
      </a-card>
    </div>
  </base-breadcrumb>
</template>

<script>
import { 
  statisticsList, 
  statisticsOrgTree,
  statisticsPointTypeTree,
  statisticsProjectSubTree,
  statisticsProjectTypeTree,
  statisticsRespAreaNodeTree,
} from '@/api/quality/reality' // api

const searchArr = [
  // 搜索框
  {
    name: '测量时间',
    type: 'dateRange',
    value: 'time',
    attr: {
      rangeFormat: ['startDate', 'endDate'],
    },
  },
]
const columns = [
  {
    title: '层级',
    dataIndex: 'name',
  },
  {
    title: '测量总数',
    dataIndex: 'total',
  },
  {
    title: '合格率',
    dataIndex: 'rate',
  },
  {
    title: '公司',
    children: [
      {
        title: '测量总数',
        dataIndex: 'coTotal',
      },
      {
        title: '合格率',
        dataIndex: 'coRate',
      },
    ]
  },
  {
    title: '分公司',
    children: [
      {
        title: '测量总数',
        dataIndex: 'bcTotal',
      },
      {
        title: '合格率',
        dataIndex: 'bcRate',
      },
    ]
  },
  {
    title: '项目',
    children: [
      {
        title: '测量总数',
        dataIndex: 'pdTotal',
      },
      {
        title: '合格率',
        dataIndex: 'pdRate',
      },
    ]
  },
]

export default {
  name:'a'+ Date.now(),
  components: {
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      statisticsListLoading: false,
      replaceFields: {
        children:'children', 
        title:'name', 
        key:'id' 
      },
      dataRefLeft: null,
      statisticsListLockLeftId: '',
      statisticsListLockRightId: '',
      lockLeft: false,
      spinningLeft: false,
      autoExpandParentLeft: true,
      dataListLeft: [],
      expandedKeysLeft: [],
      treeDataLeft: [],
      searchValueLeft: '',
      dataRefRight: null,
      lockRight: false,
      spinningRight: false,
      autoExpandParentRight: true,
      dataListRight: [],
      expandedKeysRight: [],
      treeDataRight: [],
      searchValueRight: '',
      details: {},
    }
  },
  created() {
    this.statisticsOrgTree()
    this.statisticsProjectTypeTree()
  },
  methods: {
    // 搜索
    search(value) {
      value && (this.queryParam = value)
      if (!this.statisticsListLoading) {
        this.statisticsList()
      }
    },
    // 提交汇总统计
    statisticsList() {
      if (!this.lockLeft && !this.lockRight) {
        this.$message.error('组织架构或工程构成未锁定！');
        return false
      }
      if (!this.dataRefLeft) {
        this.$message.error('组织架构未选定！');
        return false
      }
      if (!this.dataRefRight) {
        this.$message.error('工程构成未选定！');
        return false
      }
      const query = {
        leftMark: this.dataRefLeft.mark, // 左树表示符号 0 组织机构 1 检查区域
        leftTreeId: this.dataRefLeft.id, // 左树id
        lock: this.lockLeft ? 0 : 1, // 锁 0 锁左 1锁右
        markId: this.lockLeft? this.dataRefLeft.markId : this.dataRefRight.markId, // 和mark配合传入如果是分部分项 mark = 3，则有工程类别ID如果是检查区域 mark = 1，则是项目ID如果是检查项 mark = 5 ，则是点位id如果是点位 mark = 4 ，则是分部分项ID
        partId: this.dataRefRight.partId,// 分部分项ID - 这个参数主要是传检查项 必传，其他可以不传
        rightMark: this.dataRefRight.mark,
        rightTreeId: this.dataRefRight.id,
        ...this.queryParam
      }
      this.statisticsListLoading = true
      statisticsList(query).then(res => {
        if (res.data) {
          for (let key in res.data) {
            if (res.data[key] !== null) {
              if (Array.isArray(res.data[key])) {
                res.data[key] = this.handleTreeData(res.data[key])
              } else {
                res.data[key] = this.handleTreeData([res.data[key]])
              }
            }
          }
          this.details = res.data
        }
        this.statisticsListLoading = false
      }).catch(() => {
        this.statisticsListLoading = false
      })
    },
    // 最后一个节点 如果children = [] 树有+ 展开是空的
    handleTreeData(rootData) {
      const fn = (data) => {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children) {
              if (data[i].children.length < 1) {
              data[i].children = undefined;
            } else {
              fn(data[i].children)
            }
          }
        }
      }
      fn(rootData)
      return rootData;
    },
    // 操作栏
    handleManage(record) {
      let query = {}
      if (record && record.projectId) {
        query.projectId = record.projectId
      }
      this.$router.push({
        name: '/quality/measuredAmount/statisticalAnalysis/statisticalAnalysisEdit',
        query,
      })
    },
    /**
    * 设置锁定的部分不能选择
    * **/
    setTreeDisabledLeft(tree) {
      tree.forEach((item) => {
        item.scopedSlots = { title: 'title' }
        if (this.lockLeft) {
          if (this.dataRefLeft && this.dataRefLeft.id === item.id) {
            item.disabled	 = false
          } else {
            item.disabled	 = true
          }
        } else {
          item.disabled	 = false
        }
        if (item[this.replaceFields.children] && item[this.replaceFields.children].length) {
          this.setTreeDisabledLeft(item[this.replaceFields.children])
        }
      })
    },
    /**
    * 设置锁定的部分不能选择
    * **/
    setTreeDisabledRight(tree) {
      tree.forEach((item) => {
        item.scopedSlots = { title: 'title' }
        if (this.lockRight) {
          if (this.dataRefRight && this.dataRefRight.id === item.id) {
            item.disabled	 = false
          } else {
            item.disabled	 = true
          }
        } else {
          item.disabled	 = false
        }
        if (item[this.replaceFields.children] && item[this.replaceFields.children].length) {
          this.setTreeDisabledRight(item[this.replaceFields.children])
        }
      })
    },
    // 左-组织树
    statisticsOrgTree() {
      this.spinningLeft = true
      statisticsOrgTree().then(res => {
        if (res.data) {
          this.treeDataLeft.push(res.data)
          this.setTreeDisabledLeft(this.treeDataLeft)
        }
        this.spinningLeft = false
      }).catch(() => {
        this.spinningLeft = false
      })
    },
    // 加载左侧树
    onLoadDataLeft(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.flag == 'CK_NODE' && (!treeNode.dataRef.children || (treeNode.dataRef.children && treeNode.dataRef.children.length == 0))) {
          statisticsRespAreaNodeTree({projectId: treeNode.dataRef.id}).then(res => {
            if (res.data) {
              if (!treeNode.dataRef.children) {
                treeNode.dataRef.children = []
              }
              treeNode.dataRef.children = res.data;
              this.treeDataLeft = [...this.treeDataLeft];
              this.setTreeDisabledLeft(this.treeDataLeft)
              this.treeDataLeft.push({name: '', id: 'testLeft'}) // 要不不会触发重新更新数据
              setTimeout(() => {
                this.treeDataLeft = this.treeDataLeft.filter(item => item.id !== 'testLeft')
              })
            }
            resolve();
          }).catch(() => {
            resolve();
          })
        } else {
          resolve();
        }
      });
    },
    // 右-工程类别树
    statisticsProjectTypeTree() {
      this.spinningRight = true
      statisticsProjectTypeTree().then(res => {
        if (res.data) {
          this.treeDataRight.push(res.data)
          this.setTreeDisabledRight(this.treeDataRight)
        }
        this.spinningRight = false
      }).catch(() => {
        this.spinningRight = false
      })
    },
    // 加载右侧树
    onLoadDataRight(treeNode) {
      return new Promise((resolve) => {
        if (treeNode.dataRef.flag == 'CK_SUB' && (!treeNode.dataRef.children || (treeNode.dataRef.children && treeNode.dataRef.children.length == 0))) {
          statisticsProjectSubTree({projectTypeId: treeNode.dataRef.id}).then(res => {
            if (res.data) {
              if (!treeNode.dataRef.children) {
                treeNode.dataRef.children = []
              }
              treeNode.dataRef.children = res.data;
              this.treeDataRight = [...this.treeDataRight];
              this.setTreeDisabledRight(this.treeDataRight)
              this.treeDataRight.push({name: '', id: 'testRight'}) // 要不不会触发重新更新数据
              setTimeout(() => {
                this.treeDataRight = this.treeDataRight.filter(item => item.id !== 'testRight')
              })
            }
            resolve();
          }).catch(() => {
            resolve();
          })
        } else if (treeNode.dataRef.flag == 'CK_POINT' && (!treeNode.dataRef.children || (treeNode.dataRef.children && treeNode.dataRef.children.length == 0))) {
          statisticsPointTypeTree({partId: treeNode.dataRef.id}).then(res => {
            if (res.data) {
              if (!treeNode.dataRef.children) {
                treeNode.dataRef.children = []
              }
              treeNode.dataRef.children = res.data;
              this.treeDataRight = [...this.treeDataRight];
              this.setTreeDisabledRight(this.treeDataRight)
              this.treeDataRight.push({name: '', id: 'testRight'}) // 要不不会触发重新更新数据
              setTimeout(() => {
                this.treeDataRight = this.treeDataRight.filter(item => item.id !== 'testRight')
              })
            }
            resolve();
          }).catch(() => {
            resolve();
          })
        } else {
          resolve();
        }
      });
    },
    // 左侧树展开
    onExpandLeft(expandedKeys) {
      this.expandedKeysLeft = expandedKeys;
      this.autoExpandParentLeft = false;
    },
    // 右侧树展开
    onExpandRight(expandedKeys) {
      this.expandedKeysRight = expandedKeys;
      this.autoExpandParentRight = false;
    },
    // 锁定 解锁 功能
    lockChange(type) {
      if (type === 'left') {
        if (this.lockLeft) {
          this.lockLeft = !this.lockLeft
        } else {
          if (this.lockRight) {
            this.$message.error('工程构成已锁定！');
          } else {
            if (!this.dataRefLeft) {
              this.$message.error('组织架构未选定！');
              return false
            }
            this.lockLeft = !this.lockLeft
          }
        }
        this.setTreeDisabledLeft(this.treeDataLeft)
        this.statisticsListLockLeftId = this.dataRefLeft.id
        this.statisticsListLockRightId = ''
        this.treeDataLeft.push({name: '', id: 'testLeft'}) // 要不不会触发重新更新数据
        setTimeout(() => {
          this.treeDataLeft = this.treeDataLeft.filter(item => item.id !== 'testLeft')
        })
      } else {
        if (this.lockRight) {
          this.lockRight = !this.lockRight
        } else {
          if (this.lockLeft) {
            this.$message.error('组织架构已锁定！');
          } else {
            if (!this.dataRefRight) {
              this.$message.error('组织架构未选定！');
              return false
            }
            this.lockRight = !this.lockRight
          }
        }
        this.setTreeDisabledRight(this.treeDataRight)
        this.statisticsListLockRightId = this.dataRefRight.id
        this.statisticsListLockLeftId = ''
        this.treeDataRight.push({name: '', id: 'testRight'}) // 要不不会触发重新更新数据
        setTimeout(() => {
          this.treeDataRight = this.treeDataRight.filter(item => item.id !== 'testRight')
        })
      }
    },
    // 树平铺
    generateList(data, dataList) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const title = node[this.replaceFields.title];
        const key = node[this.replaceFields.key];
        dataList.push({ [this.replaceFields.key]: key, [this.replaceFields.title]: title });
        if (node.children) {
          this.generateList(node.children, dataList);
        }
      }
    },
    getParentKey(key, tree) {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item[this.replaceFields.key] === key)) {
            parentKey = node[this.replaceFields.key];
          } else if (this.getParentKey(key, node.children)) {
            parentKey = this.getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    },
    onSearchLeft(e) {
      if (this.treeDataLeft.length < 1) {
        return false
      }
      const value = e.target.value;
      this.dataListLeft = []
      this.generateList(this.treeDataLeft, this.dataListLeft)
      const expandedKeysLeft = this.dataListLeft
        .map(item => {
          if (item[this.replaceFields.title].indexOf(value) > -1) {
            return this.getParentKey(item[this.replaceFields.key], this.treeDataLeft);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeysLeft,
          searchValueLeft: value,
          autoExpandParentLeft: true,
        });
    },
    onSearchRight(e) {
      if (this.treeDataRight.length < 1) {
        return false
      }
      const value = e.target.value;
      this.dataListRight = []
      this.generateList(this.treeDataRight, this.dataListRight)
      const expandedKeysRight = this.dataListRight
        .map(item => {
          if (item[this.replaceFields.title].indexOf(value) > -1) {
            return this.getParentKey(item[this.replaceFields.key], this.treeDataRight);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
        Object.assign(this, {
          expandedKeysRight,
          searchValueRight: value,
          autoExpandParentRight: true,
        });
    },
    onSelectLeft(selectedKeys, info) {
      this.dataRefLeft = info.node.dataRef
      // console.log('selected', selectedKeys, info);
    },
    onSelectRight(selectedKeys, info) {
      this.dataRefRight = info.node.dataRef
      // console.log('selected', selectedKeys, info);
    },
  },
}
</script>

<style lang="less" scoped>
  .statistics-left {
    display: flex;
    margin-bottom: 10px;
  }
  .statistics-top {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  .searchIcon2 {
    position: absolute;
    top: 8px;
    right: 10px;
    z-index: 100;
    font-size: 16px;
  }
  /deep/ .ant-tree li .ant-tree-node-content-wrapper {
  white-space: pre-wrap;
  height: auto;
  width: calc(100% - 26px);
}
</style>